package com.yhn.init.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yhn.init.common.DeleteRequest;
import com.yhn.init.common.ErrorCode;
import com.yhn.init.exception.BusinessException;
import com.yhn.init.exception.ThrowUtils;
import com.yhn.init.mapper.RoleMapper;
import com.yhn.init.model.dto.role.RoleAddRequest;
import com.yhn.init.model.dto.role.RoleQueryRequest;
import com.yhn.init.model.dto.role.RoleUpdateRequest;
import com.yhn.init.model.entity.Role;
import com.yhn.init.model.vo.RoleVO;
import com.yhn.init.service.RoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service("roleService")
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Override
    public Page<RoleVO> queryPage(RoleQueryRequest roleQueryRequest) {
        if (roleQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long current = roleQueryRequest.getCurrent();
        long size = roleQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Role> rolePage = this.page(new Page<>(current, size),
                this.getQueryWrapper(roleQueryRequest));
        Page<RoleVO> roleVOPage = new Page<>(current, size, rolePage.getTotal());
        List<RoleVO> roleVO = this.getRoleVO(rolePage.getRecords());
        roleVOPage.setRecords(roleVO);
        return roleVOPage;
    }


    @Override
    public QueryWrapper<Role> getQueryWrapper(RoleQueryRequest roleQueryRequest) {
        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        // 如果请求对象为空，直接返回一个空的查询包装器
        if (roleQueryRequest == null) {
            return queryWrapper;
        }
        // 从请求对象中获取各项查询条件
        Long id = roleQueryRequest.getId();
        queryWrapper.eq(id != null && id > 0, "id", id);
        return queryWrapper;
    }

    /**
     * 获取脱敏对象集合
     *
     * @param roleList 查询请求
     * @return 脱敏对象集合
     */
    @Override
    public List<RoleVO> getRoleVO(List<Role> roleList) {
        if (CollUtil.isEmpty(roleList)) {
            return new ArrayList<>();
        }
        return roleList.stream().map(this::getRoleVO).collect(Collectors.toList());
    }


    /**
     * 将对象转化为脱敏对象
     *
     * @param role 原对象
     * @return 脱敏对象
     */
    @Override
    public RoleVO getRoleVO(Role role) {
        if (role == null) {
            return null;
        }
        RoleVO roleVO = new RoleVO();
        BeanUtils.copyProperties(role, roleVO);
        return roleVO;
    }

    /**
     * 根据ID获取信息
     *
     * @param id id
     * @return 实体信息
     */
    @Override
    public RoleVO getInfoById(Long id) {
        Role role = this.getById(id);
        if (role == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "没有对应的信息");
        }
        return getRoleVO(role);
    }

    /**
     * 保存信息
     *
     * @param roleAddRequest 添加请求
     * @return 新生成的ID
     */
    @Override
    @Transactional
    public Long saveRole(RoleAddRequest roleAddRequest) {
        if (roleAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Role role = new Role();
        BeanUtils.copyProperties(roleAddRequest, role);
        boolean result = this.save(role);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return role.getId();
    }


    /**
     * 修改信息
     *
     * @param roleUpdateRequest 修改请求
     * @return 是否修改成功
     */
    @Override
    @Transactional
    public Boolean updateRole(RoleUpdateRequest roleUpdateRequest) {
        if (roleUpdateRequest == null || roleUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Role role = new Role();
        BeanUtils.copyProperties(roleUpdateRequest, role);
        long id = roleUpdateRequest.getId();
        // 判断是否存在
        Role oldRole = this.getById(id);
        ThrowUtils.throwIf(oldRole == null, ErrorCode.NOT_FOUND_ERROR);
        boolean result = this.updateById(role);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return result;
    }

    /**
     * 删除信息
     *
     * @param deleteRequest 删除请求
     * @return 是否修改成功
     */
    @Override
    public Boolean deleteById(DeleteRequest deleteRequest) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long id = deleteRequest.getId();
        // 判断是否存在
        boolean b = this.removeById(id);
        ThrowUtils.throwIf(!b, ErrorCode.NOT_FOUND_ERROR);
        return b;
    }


    /**
     * 批量删除
     *
     * @param ids 批量删除的IDS
     * @return 是否删除成功
     */
    @Override
    @Transactional
    public Boolean deleteBatchByIds(Long[] ids) {
        if (ids == null || ids.length == 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean b = this.removeByIds(Arrays.asList(ids));
        ThrowUtils.throwIf(!b, ErrorCode.NOT_FOUND_ERROR);
        return b;
    }
}
